<template>
  <el-dialog :model-value="internalVisible" :title="title" width="40%" @close="handleClose">
    <div>
      <!-- 根据实际内容动态渲染 -->
      <slot :validateForm="validateForm"></slot>
    </div>
    <!-- 根据 type 属性决定是否渲染按钮 -->
    <template v-if="showConfirmButton" #footer>
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits } from 'vue'

// 定义 props
const props = defineProps({
  title: {
    type: String,
    default: '对话框标题',
  },
  type: {
    type: String,
    default: 'form',
  },
  visible: {
    type: Boolean,
    default: false,
  },
  showConfirmButton: {
    type: Boolean,
    default: true,
  },
  onClose: {
    type: Function,
    default: () => { },
  },
  onConfirm: {
    type: Function,
    default: () => { },
  },
})

// 定义 emits
const emit = defineEmits(['close', 'confirm'])

// 内部状态
const internalVisible = ref(false)

// 监听 prop 的 visible 同步到内部状态
watch(
  () => props.visible,
  (newVal) => {
    internalVisible.value = newVal
  },
  { immediate: true }
)

// 关闭对话框的处理函数
const handleClose = () => {
  emit('close')
  internalVisible.value = false // 隐藏对话框
}

// 提交的处理函数
const handleSubmit = () => {
  if (props.type === 'form') {
    validateForm((valid: boolean) => {
      if (valid) {
        emit('confirm')
        internalVisible.value = false // 隐藏对话框
      } else {
        console.log('表单验证失败!')
      }
    })
  } else {
    emit('confirm')
    internalVisible.value = false // 隐藏对话框
  }
}

// 表单验证函数
const validateForm = (callback: (valid: boolean) => void) => {
  const formRef = ref()
  if (formRef.value) {
    formRef.value.validate(callback)
  } else {
    // 如果没有表单，直接通过验证
    callback(true)
  }
}
</script>
